package com.ocom.payconfig.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.constant.UnifiendPayUrl;
import com.ocom.common.entity.card.EntityXfGoodListOrg;
import com.ocom.common.entity.card.EntityXfGoodsListProcess;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.entity.payconfig.EntityMqttDevice;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.food.OrderRefundRequest;
import com.ocom.common.request.payconfig.mealorder.RefundOrderDishesRequest;
import com.ocom.common.request.payhandle.FeeRefundRequest;
import com.ocom.common.request.payhandle.GetRecordProcessRequest;
import com.ocom.common.request.xfrecde.GetXfGoodListRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.NumConvertUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.payconfig.client.PayhandleClientService;
import com.ocom.payconfig.client.XfRecordFeign;
import com.ocom.payconfig.service.MqttDeviceService;
import com.ocom.payconfig.service.XfRecordProcessService;
import com.ocom.payconfig.utils.WeiMiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

import com.ocom.payconfig.service.XfGoodsListProcessService;
@RestController
@Slf4j
public class WeiMiController {

    @Autowired
    private XfRecordProcessService recordProcessService;

    @Autowired
    private XfRecordFeign xfRecordFeign;
    @Autowired
    private XfGoodsListProcessService xfGoodsListProcessService;

    @Autowired
    private MqttDeviceService mqttDeviceService;

    @Autowired
    private PayhandleClientService payhandleClientService;

    @PostMapping(PayConfigUrl.URL_shipment)
    public Result shipment(@RequestBody Map<String, Object> map){
        JSONArray array = JSON.parseArray(JSON.toJSONString(map.get("aisleGoodsList")));
        List<JSONObject> aisleGoodsList = new ArrayList<>();
        array.forEach(o->{
            JSONObject jsonObjectA = JSON.parseObject(JSON.toJSONString(o));
            jsonObjectA.put("aisleCode",jsonObjectA.getString("code"));
            jsonObjectA.remove("code");
            aisleGoodsList.add(jsonObjectA);
        });
        Map<String,Object> params = new HashMap<>();
        params.put("userId",map.get("pId"));
        params.put("tradeNo",map.get("tradeNo"));
        params.put("deviceCode",map.get("mqttDeviceNo"));
        params.put("payChannelCodeInt",11001);
        params.put("authType",7);
        params.put("aisleGoodsList",aisleGoodsList);
        params.put("payEndTime",System.currentTimeMillis());
        String re= WeiMiUtil.shipment(params);
        return ResultUtil.success(re);
    }
    @PostMapping(PayConfigUrl.URL_weimiDeviceInfo)
    public Result deviceInfo(@RequestBody Map<String, Object> map){
        Map<String,Object> params = new HashMap<>();
        params.put("deviceCodes",map.get("mqttDeviceNo"));
        String result = WeiMiUtil.device(params);
        JSONObject jsonObject = JSON.parseObject(result);

        return ResultUtil.success();
    }

    @PostMapping(PayConfigUrl.URL_weimiCallBack)
    public String callBack(@RequestBody JSONObject jsonObject){
        Long comId = 0l ;
        EntityMqttDevice entityMqttDevice = new EntityMqttDevice();
        entityMqttDevice.setMqttDeviceNo(jsonObject.getString("deviceCode"));
        EntityMqttDevice entityMqttDeviceA = mqttDeviceService.selectDevice(1L,entityMqttDevice);
        if(ObjectUtil.isNotEmpty(entityMqttDeviceA)){
            comId = entityMqttDeviceA.getComId();
        }else{
            entityMqttDeviceA = mqttDeviceService.selectDevice(600L,entityMqttDevice);
           if(ObjectUtil.isNotEmpty(entityMqttDeviceA)){
               comId = entityMqttDeviceA.getComId();
           }
        }
        if(comId.equals(0L)){
            log.info("微米回传：comId出错【{}】，参数【{}】",comId,jsonObject.toJSONString());
            return "{\"code\":200,\"msg\":\"success\"}";
        }
        EntityXfRecordProcess xfRecordProcess = recordProcessService.selectTradeNo(comId, jsonObject.getString("tradeNoOut"), null);

        JSONObject jsonObjectA = new JSONObject();
        jsonObjectA.put("comId",comId);
        jsonObjectA.put("orderNo",jsonObject.getString("tradeNoOut"));

        List<EntityXfGoodsListProcess> xfGoodsListProcesseList =   this.xfGoodsListProcessService.getXfGoodsList(comId, jsonObject.getString("tradeNoOut"));;
        EntityXfGoodsListProcess entityXfGoodsListProcess = null;
        String receiptName = jsonObject.getString("tradeNoIn") + "||" + jsonObject.getString("shipmentStatus");
        Integer receiptId = jsonObject.getInteger("shipmentStatus");
        for (int i = 0; i < xfGoodsListProcesseList.size(); i++) {
            if(receiptName.equals(xfGoodsListProcesseList.get(i).getReceiptName())){
                entityXfGoodsListProcess = xfGoodsListProcesseList.get(i);
                break;
            }
        }
        if(ObjectUtil.isEmpty(entityXfGoodsListProcess)){
            for (int i = 0; i < xfGoodsListProcesseList.size(); i++) {
                String[] pr = StrUtil.split(xfGoodsListProcesseList.get(i).getDishesName(),"||");
                if(StrUtil.isBlank(xfGoodsListProcesseList.get(i).getReceiptName()) && jsonObject.getString("goodsId").equals(pr[1])){
                    entityXfGoodsListProcess = xfGoodsListProcesseList.get(i);
                    entityXfGoodsListProcess.setReceiptName(receiptName);
                    entityXfGoodsListProcess.setReceiptId(receiptId);
                    break;
                }
            }
        }

        if(ObjectUtil.isNotEmpty(entityXfGoodsListProcess)){
            this.xfGoodsListProcessService.updateById(comId,entityXfGoodsListProcess);
        }

        GetXfGoodListRequest request = new GetXfGoodListRequest();
        request.setComId(comId);
        request.setOrderNo(jsonObject.getString("tradeNoOut"));
        request.setMonthValue(xfRecordProcess.getMonthValue());
        Result resultA = this.xfRecordFeign.getXfGoodList(request);

        //挑选一个未填写的菜品
        if(resultA.getCode() == 200){
            List<EntityXfGoodsListProcess> xfGoodsListProcesseListA = JSON.parseArray(JSON.toJSONString(resultA.getData()),EntityXfGoodsListProcess.class);
            EntityXfGoodsListProcess entityXfGoodsListProcessA = null;
            for (int i = 0; i < xfGoodsListProcesseListA.size(); i++) {
                if(receiptName.equals(xfGoodsListProcesseListA.get(i).getReceiptName())){
                    entityXfGoodsListProcessA = xfGoodsListProcesseListA.get(i);
                    break;
                }
            }
            if(ObjectUtil.isEmpty(entityXfGoodsListProcessA)){
                for (int i = 0; i < xfGoodsListProcesseListA.size(); i++) {
                    String[] pr = StrUtil.split(xfGoodsListProcesseListA.get(i).getDishesName(),"||");
                    if(StrUtil.isBlank(xfGoodsListProcesseListA.get(i).getReceiptName()) && jsonObject.getString("goodsId").equals(pr[1])){
                        entityXfGoodsListProcessA = xfGoodsListProcesseListA.get(i);
                        entityXfGoodsListProcessA.setReceiptName(receiptName);
                        entityXfGoodsListProcessA.setReceiptId(receiptId);
                        break;
                    }
                }
            }
            if(ObjectUtil.isNotEmpty(entityXfGoodsListProcessA)){
                EntityXfGoodListOrg entityXfGoodListOrg = Convert.convert(EntityXfGoodListOrg.class,entityXfGoodsListProcessA);
                this.xfRecordFeign.updateGoodsById(entityXfGoodListOrg);
            }
        }
        return "{\"code\":200,\"msg\":\"success\"}";
    }

    @PostMapping(PayConfigUrl.URL_weimiAutoRefund)
    public Result autoRefund(@RequestBody JSONObject jsonObject){
        Long comId = jsonObject.getLong("comId");
        Date beginTime = DateUtil.offset(new Date(), DateField.DAY_OF_MONTH,-1);
        Date endTime = DateUtil.offset(new Date(), DateField.MINUTE,-5);
        EntityXfGoodsListProcess entityXfGoodsListProcess = new EntityXfGoodsListProcess();
        List<EntityXfGoodsListProcess> goodsListProcesses = this.xfGoodsListProcessService.getXfGoodsList(comId,entityXfGoodsListProcess,beginTime,endTime);
        goodsListProcesses.forEach(entityXfGoodsListProcess1 -> {
            OrderRefundRequest request = new OrderRefundRequest();
            request.setComId(comId);
            request.setOrderNo(entityXfGoodsListProcess1.getOrderNo());
            request.setGoodsId(entityXfGoodsListProcess1.getDishesId().longValue());
            GetRecordProcessRequest processRequest = new GetRecordProcessRequest();
            processRequest.setCompanyId(request.getComId());
            processRequest.setTradeNo(request.getOrderNo());
            Result result = payhandleClientService.getRecordProcess(processRequest);
            if (200 != result.getCode()) {
                return;
            }
            EntityXfRecordProcess entityXfRecordProcess = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfRecordProcess.class);

            FeeRefundRequest feeRefund = new FeeRefundRequest();
            feeRefund.setCompanyId(request.getComId());
            feeRefund.setFeeItemId(request.getGoodsId().intValue());
            feeRefund.setPId(0);
            feeRefund.setRefundAmount(Math.abs(entityXfRecordProcess.getRealMoney().intValue()));
            feeRefund.setOrigTradeNo(request.getOrderNo());
            feeRefund.setTradeNo(new Date().getTime() + "C" + request.getComId() + "P" + entityXfRecordProcess.getPId());
            feeRefund.setCheck(false);
            result = payhandleClientService.paraRefundB(feeRefund);

            if (200 != result.getCode()) {
                return ;
            }

            RefundOrderDishesRequest dishesRequest = new RefundOrderDishesRequest();
            dishesRequest.setOrderNo(request.getOrderNo());
            dishesRequest.setComId(request.getComId());
            dishesRequest.setGoodsId(Lists.newArrayList(request.getGoodsId().intValue()));
            dishesRequest.setMonthValue(entityXfRecordProcess.getMonthValue());

            xfGoodsListProcessService.refund(request.getComId(),request.getOrderNo(),Lists.newArrayList(request.getGoodsId().intValue()));

            xfRecordFeign.refund(dishesRequest);

        });
        return ResultUtil.success();
    }
}
